import store from "@/store";

export default {
	install(Vue) {
		/**
		 * @param {Date} time
		 * @param {String} pattern  '{y}-{m}-{d} {h}:{i}:{s}'
		 * @description 日期格式化
		 */
		Vue.prototype.parseTime = (time, pattern) => {
			if (arguments.length === 0 || !time) {
			    return null
			  }
			  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
			  let date
			  if (typeof time === 'object') {
			    date = time
			  } else {
			    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			      time = parseInt(time)
			    } else if (typeof time === 'string') {
			      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
			    }
			    if ((typeof time === 'number') && (time.toString().length === 10)) {
			      time = time * 1000
			    }
			    date = new Date(time)
			  }
			  const formatObj = {
			    y: date.getFullYear(),
			    m: date.getMonth() + 1,
			    d: date.getDate(),
			    h: date.getHours(),
			    i: date.getMinutes(),
			    s: date.getSeconds(),
			    a: date.getDay()
			  }
			  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
			    let value = formatObj[key]
			    // Note: getDay() returns 0 on Sunday
			    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
			    if (result.length > 0 && value < 10) {
			      value = '0' + value
			    }
			    return value || 0
			  })
			  return time_str
		};

		// 获取当前打开过的页面路由
		Vue.prototype.$getPagePath = () => {
			let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			let curRoute = routes[routes.length - 1].route; //获取当前页面路由
			let curParam = routes[routes.length - 1].options; //获取路由参数
			// 拼接参数
			if (Object.getOwnPropertyNames(curParam).length != 0) {
				let param = '';
				for (let key in curParam) {
					param += '&' + key + '=' + curParam[key];
				}
				var path = curRoute + '?' + param.slice(1);
				return uni.setStorageSync('path', '/' + path);
			} else {
				return uni.setStorageSync('path', '/' + curRoute);
			}
		};

		/**
		 * @param {String} url
		 * @description 统一跳转
		 */
		Vue.prototype.navigateTo = (url) => {
			uni.navigateTo({
				url: '/'+url,
			})
		};

		/**
		 *  关闭当前页面并跳转
		 */
		Vue.prototype.redirectTo = (url) => {
			uni.redirectTo({
				url: '/'+url,
			})
		};

		Vue.prototype.reLaunch = (url) => {
			uni.reLaunch({
				url: '/'+url,
			})
		};

		Vue.prototype.switchTab = (url) => {
			uni.switchTab({
				url: '/'+url,
			})
		};
		// 返回上一页
		Vue.prototype.navigateBack = (time, num) => {
			time = time ? time : 1000;
			num = num ? num : 1;
			return setTimeout(res => {
				uni.navigateBack({
					delta: Number(num)
				})
			}, time);
		};

		// 显示消息提示框。
		Vue.prototype.$toast = (value, icon) => {
			icon = icon ? icon : 'none';
			uni.showToast({
				title: value,
				duration: 2000,
				icon
			});
		};
		// 显示 loading 提示框
		Vue.prototype.$showLoading = (value) => {
			uni.showLoading({
				title: value
			});
		};
		Vue.prototype.$hideLoading = () => {
			setTimeout(function () {
				uni.hideLoading();
			}, 1000);
		};
		// 根据数据字典 展示枚举内容
		Vue.prototype.dictKey = (dict, keys, keycode, keyname) => {
			keycode = keycode ? keycode : "value";
			keyname = keyname ? keyname : "label";
			let key = keys;
			if ((key == null || key == "" || key == undefined) && key != 0) {
				return '';
			}

			key = key != 0 ? String(key).split(',') : '0';
			let names = [];
			if (key.length != 0) {
				if (Array.isArray(dict)) {
					for (let i = 0; i < dict.length; i++) {
						for (let k = 0; k < key.length; k++) {
							if (dict[i][keycode] == key[k]) {
								names.push(dict[i][keyname]);
							}
						}
					}
				} else {
					for (let i in dict) {
						for (let k = 0; k < key.length; k++) {
							if (i == key[k]) {
								names.push(dict[i]);
							}
						}
					}

				}
				return names.join(',');
			} else if (key == 0) {
				for (let i in dict) {
					if (i == 0) {
						names.push(dict[i][keyname]);
					}
				}
				return names.join(',');
			} else {
				return '';
			}
		};
		/*
		 * json数组去重
		 * @param: {Array} jsonArr 去重之前的数组
		 * @param  {String} field  需要去重的字段值
		 */
		Vue.prototype.deWeight =(jsonArr, field)=> {
		  // 数组长度小于2 或 没有指定去重字段 或 不是json格式数据
		  if (jsonArr.length < 2 || !field || typeof jsonArr[0] !== "object")
		    return jsonArr;
		  let uniqueArr = [jsonArr[0]];
		  field = field ? field : "id";
		  for (let i = 1; i < jsonArr.length; i++) {
		    let item = jsonArr[i];
		    let repeat = false; // 标识位
		    for (let j = 0; j < uniqueArr.length; j++) {
		      if (item[field] && item[field] == uniqueArr[j][field]) {
		        repeat = true;
		        break;
		      }
		    }
		    if (!repeat) {
		      uniqueArr.push(item);
		    }
		  }
		  return uniqueArr;
		};

	}
}
